<?php

namespace Framework\Foundation\Response;

class ResponseProcessor
{
    /**
     * @var \GuzzleHttp\Psr7\Response
     */
    public $response;

    public function send($response)
    {
        $this->response = $response;
        $this->sendHeader();
        $this->sendContent();
    }

    public function sendHeader()
    {
        // headers have already been sent by the developer
        if (headers_sent()) {
            return $this;
        }

        // status
        header(sprintf(
            'HTTP/%s %s %s',
            $this->response->getProtocolVersion(),
            $this->response->getStatusCode(),
            $this->response->getReasonPhrase()
        ));

        // headers
        $headers = $this->response->getHeaders();
        if (empty($headers)) {
            return true;
        }

        ksort($headers);
        $max = max(array_map('strlen', array_keys($headers))) + 1;
        foreach ($headers as $name => $values) {
            $name = ucwords($name, '-');
            // set cookies
            if ($name == 'Set-Cookie') {
                foreach ($headers['set-cookie'] as $cookie) {
                    header('Set-Cookie: ' . $cookie);
                }
                continue;
            }
            // other headers
            foreach ($values as $value) {
                $header = sprintf("%-{$max}s %s\r\n", $name . ':', $value);
                header($header);
            }
        }
//        foreach ($header as $name => $values) {
//            $replace = 0 === strcasecmp($name, 'Content-Type');
//            foreach ($values as $value) {
//                header($name . ': ' . $value, $replace);
//            }
//        }
    }

    public function sendContent($content = null, $type = 'json')
    {
        echo $this->response->getBody();
    }
}
